<template>
  <div class="app-container">
    <div
      v-show="
        !modifyDeliverInfo.visible &&
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !purchOrder.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-receiptNumber="scope">
            <el-input
              v-model="filterInfo.query.queryParams.receiptNumber"
              type="input"
              placeholder="请输入发票号汇总"
            ></el-input>
          </template>
          <template v-slot:filter-noneReceiptNumber="scope">
            <el-select
              @change="search"
              clearable
              placeholder="请选择开票状态"
              v-model="filterInfo.query.queryParams.noneReceiptNumber"
            >
              <el-option
                :value="item.code"
                v-for="(item, index) in selectModeOption"
                :key="index"
                :label="item.name"
              />
            </el-select>
          </template>
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-storage>
            <el-button
              :disabled="!canStorage"
              :loading="btnLoading"
              @click="storage()"
              >入库</el-button
            >
          </template>
          <template v-slot:filter-revoke>
            <el-button :disabled="!canStorage" @click="revoke()"
              >撤回</el-button
            >
          </template>
          <template v-slot:filter-pendStoreRevoke>
            <el-button
              :disabled="!canPendStoreRevoke"
              @click="pendStoreRevoke()"
              >撤销</el-button
            >
          </template>
          <template v-slot:filter-del>
            <el-button :disabled="!canSubmit" @click="remove()">删除</el-button>
          </template>
          <template v-slot:filter-byDeliverOrder>
            <el-button @click="addBydeliver()">发货单导入</el-button>
          </template>
          <template v-slot:filter-estimated>
            <el-button @click="addEstimated()">暂估收货</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('receiving:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
        <template v-slot:col-purchOrderNo="scope">
          <span
            v-if="
              $permission('purchOrder:detail') &&
              scope.row.purch_application_show
            "
            class="slip-edit"
            @click="showpurchOrderNoDetail(scope.row)"
            >{{ scope.row.purchOrderNo }}</span
          >
          <span v-else>{{ scope.row.purchOrderNo || '-' }}</span>
        </template>
      </table-container>
    </div>

    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="close"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-depotName>{{
          dialogInfo.row.depotName
        }}</template>
        <template v-slot:form-deptName>{{ dialogInfo.row.deptName }}</template>
        <template v-slot:form-transferDepotName>
          <el-input
            v-model="formInfo.data.transferDepotName"
            class="not-mongolia"
            type="input"
            :required="true"
            :disabled="true"
            placeholder="请选择入库仓库"
          >
            <template #append>
              <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
      <dialog-table
        v-if="dialogTableInfo.data.length"
        v-model:data="dialogTableInfo.data"
        :field-list="dialogTableInfo.fieldList"
        :highlight-row="true"
        :tab-index="true"
        :check-box="false"
        :pager="false"
        @handleEvent="handleDialogEvent"
      >
      </dialog-table>
    </page-dialog>
    <!-- 多人验证弹窗 -->
    <page-dialog
      v-if="manyPeopleInfo.visible"
      :title="manyPeopleInfo.title"
      v-model:visible="manyPeopleInfo.visible"
      :width="manyPeopleInfo.width"
      :bt-loading="manyPeopleInfo.btLoading"
      :bt-list="manyPeopleInfo.btList"
      @reset="manyPeopleClose"
    >
      <el-form ref="tableForm" :model="manyPeopleTable" style="width: 100%">
        <dialog-table
          v-model:data="manyPeopleTable.data"
          :field-list="manyPeopleTable.fieldList"
          :highlight-row="false"
          :tab-index="true"
          :check-box="false"
          :pager="false"
        >
        </dialog-table>
      </el-form>
    </page-dialog>
    <AddBydeliverOrder
      v-if="addDeliverDialog.visible"
      v-model:visible="addDeliverDialog.visible"
      :isEstimated="addDeliverDialog.isEstimated"
      @callback="addDeliverBack"
    />
    <ModifyOrder
      v-if="modifyDeliverInfo.visible"
      v-model:visible="modifyDeliverInfo.visible"
      :title="modifyDeliverInfo.title"
      :deliver-id="modifyDeliverInfo.deliverId"
      :order-id="modifyDeliverInfo.orderId"
      :receive-all="modifyDeliverInfo.receiveAll"
      :isEstimated="modifyDeliverInfo.isEstimated"
      @returnModify="search"
    ></ModifyOrder>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="search"
    ></Modify>
    <!-- 明细 -->
    <receiving-order-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :is-cargo-space-manage="detailInfo.isCargoSpaceManage"
      @returnBack="getList"
    />
    <purch-order-detail
      v-if="purchOrder.visible"
      v-model:visible="purchOrder.visible"
      :purch-order-id="purchOrder.purchOrderId"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :query="advancedSearchInfo.query"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <PageDialog
      v-show="dialogUserInfo.visible"
      :title="dialogUserInfo.title"
      v-model:visible="dialogUserInfo.visible"
      :width="dialogUserInfo.width"
      :bt-loading="dialogUserInfo.btLoading"
      :bt-list="dialogUserInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formUserInfo.ref"
        :data="formUserInfo.data"
        :field-list="formUserInfo.fieldList"
        :label-width="formUserInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </page-form>
    </PageDialog>
    <bindUDI
      v-if="bindUDIInfo.visible"
      v-model:visible="bindUDIInfo.visible"
      :tableRow="bindUDIInfo.row"
      @callback="getList"
    ></bindUDI>
  </div>
</template>

<script setup name="receivingOrder">
import {
  getReceivingOrderCustomizeListPage,
  submitReceivingOrder,
  storageReceivingOrder,
  deleteReceivingOrder,
  invalidReceivingOrder,
  stockAndTransferReceivingOrder,
  revokeReceivingOrder,
  pendStoreRevokeReceivingOrder,
  getDepotCirculationPath,
  stockAndTransferByPath,
  manyPeopleVerification,
  stockAndPutShelfReceivingOrder,
  checkReceivingOrder,
  rejectReceivingOrder,
  cancelPut,
} from '@/api/stock'
const ModifyOrder = defineAsyncComponent(() => import('./importModifyOrder'))
const Modify = defineAsyncComponent(() => import('./modify'))
const ReceivingOrderDetail = defineAsyncComponent(() => import('./detail'))
const AddBydeliverOrder = defineAsyncComponent(() =>
  import('./addBydeliverOrder')
)
const PurchOrderDetail = defineAsyncComponent(() =>
  import('../../purch/order/detail.vue')
)
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/defaultSetPreference')
)
const bindUDI = defineAsyncComponent(() => import('./bindUDI'))
const detailList = defineAsyncComponent(() => import('./detailList'))
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getRrgUserAll } from '@/api/base.js'
import { aesEncrypt } from '@/utils/aes-util.js'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
//添加产品，新增修改页的后端合并条件保持一致
const btnLoading = ref(false)
const tableLoading = ref(true)
const clearType = ref(true)
const slipSelectRequest = ref(true) // 表格相关
const time = ref([])
const addDeliverDialog = reactive({
  visible: false,
  isEstimated: false,
})
const selectModeOption = ref(
  proxy.$store.state.permission.dict['receive_receipt_order_status'] || []
)
const bindUDIInfo = ref({
  visible: false,
  row: {}
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {
      deptAuth: {
        asTbName: 'receiving_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      depotAuth: {
        asTbName: 'receiving_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      supplierAuth: {
        asTbName: 'receiving_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    queryParams: {
      showSumAmount: 1,
      printCode: 'receiving:printCode',
      withReceiptInfo: true,
      receiptNumber: null,
      noneReceiptNumber: null,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('receiving:add'),
    },
    {
      type: 'slot',
      value: 'storage',
      show: proxy.$permission('receiving:storage'),
    },
    {
      type: 'slot',
      value: 'revoke',
      show: proxy.$permission('receiving:revoke'),
    },
    {
      type: 'slot',
      value: 'pendStoreRevoke',
      show:
        proxy.$permission('receiving:backOut') &&
        proxy.$store.state.permission.systemConfig
          .material_receiving_approval == 1,
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('receiving:del'),
    },
    {
      type: 'slot',
      value: 'byDeliverOrder',
      show: proxy.$permission('receiving:byDeliverOrder'),
    },
    {
      type: 'slot',
      value: 'estimated',
      show: proxy.$permission('receiving:estimated'),
    },
  ],
})

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('receiving:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('receiving:del'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('receiving:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '审核',
        event: check,
        show:
          proxy.$store.state.permission.systemConfig
            .material_receiving_approval === 1 &&
          proxy.$permission('receiving:check'),
        ifRender: function (row) {
          return row.status === 6
        },
      },
      {
        label: '驳回',
        event: reject,
        show:
          proxy.$store.state.permission.systemConfig
            .material_receiving_approval === 1 &&
          proxy.$permission('receiving:reject'),
        ifRender: function (row) {
          return row.status === 6
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('receiving:revoke'),
        ifRender: ifRenderRevoke,
      },
      {
        label: 'UDI绑定',
        event: checkBindUDI,
        show: proxy.$permission('reveiving:bindUDI'),
        ifRender: (row) => {
          return row.status == '3' && row.udiBindStatus && row.udiBindStatus !== '1'
        },
      },
      {
        label: '撤销',
        event: pendStoreRevoke,
        show:
          proxy.$permission('receiving:backOut') &&
          proxy.$store.state.permission.systemConfig
            .material_receiving_approval == 1,
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '入库',
        event: storage,
        show: proxy.$permission('receiving:storage'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '入库并移库',
        event: showTransferDetail,
        show: proxy.$permission('receiving:stockAndTransfer'),
        ifRender: function (row) {
          return row.status === 2 && row.isCargoSpaceManage === 0
        },
      },
      {
        label: '取消上架',
        event: _cancelPut,
        show: proxy.$permission('receiving:cancelPut'),
        ifRender: function (row) {
          return row.status === 7
        },
      },
      /* {
        label: '入库并上架',
        event: storeAndPutShelf,
        show: proxy.$permission('receiving:storeAndPutShelf'),
        ifRender: function (row) {
          return row.status === 2 && row.isCargoSpaceManage === 1
        },
      }, */
    ],
  },
})

const modifyDeliverInfo = reactive({
  visible: false,
  title: '',
  orderId: '',
  deliverId: '',
  receiveAll: false,
  isEstimated: false,
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  orderId: '',
})
const detailInfo = reactive({
  visible: false,
  id: '',
  isCargoSpaceManage: '',
})
const dialogTableInfo = reactive({
  data: [],
  fieldList: [{ label: '移库路径', value: 'name' }],
})
// 弹窗相关
const dialogInfo = ref({
  title: '入库并移库',
  visible: false,
  type: '',
  width: '670px',
  btLoading: false,
  row: {},
  path: {},
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      disabled: true,
      event: stockAndTransfer,
      saveLoading: false,
      show: true,
    },
  ],
})
const dialogUserInfo = reactive({
  visible: false,
  title: '选择上架人员',
  btLoading: false,
  width: '400px',
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveputShelfUser,
      show: true,
    },
  ],
})
const formUserInfo = reactive({
  data: {
    id: '',
    putShelfUser: -2,
  },
  fieldList: [
    {
      label: '姓名',
      value: 'putShelfUser',
      type: 'select',
      filterable: true,
      list: 'userList',
      event: 'userName',
    },
  ],
})
const listTypeInfo = reactive({
  userList: [],
})
const manyPeopleInfo = reactive({
  title: '多人验证',
  visible: false,
  type: '',
  width: '670px',
  btLoading: false,
  row: {},
  path: {},
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: manyPeopleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: manyPeopleSave,
      saveLoading: false,
      show: true,
    },
  ],
})
const manyPeopleTable = reactive({
  data: [],
  fieldList: [
    {
      label: '账号',
      value: 'username',
      type: 'inputRules',
      rules: { required: true, message: '请输入账号', trigger: 'blur' },
    },
    {
      label: '密码',
      value: 'password',
      type: 'password',
      rules: { required: true, message: '请输入密码', trigger: 'blur' },
    },
  ],
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: 'id',
    idNot: '',
    status: 1,
    useTypeId: 1,
    isCargoSpaceManage: '0',
  },
})
// 表单相关
const formInfo = reactive({
  ref: null,
  data: {
    id: '',
    transferDepotName: '',
    transferDeptName: '',
    transferDepotId: '',
    transferDeptId: '',
  },
  fieldList: [
    {
      label: '入库仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '入库部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '移库入库仓库',
      value: 'transferDepotName',
      type: 'slot',
    },
    {
      label: '移库入库部门',
      value: 'transferDeptName',
      type: 'input',
      placeholder: '入库部门',
      disabled: true,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
  ],
  rules: {
    transferDepotName: [
      {
        required: true,
        message: '请输入仓库',
        trigger: 'blur',
      },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'change' },
    ],
  },
  labelWidth: '120px',
})
const purchOrder = reactive({
  visible: false,
  purchOrderId: '',
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
  query: { fiscalType: 1 },
})
let disStartDate = ref('')
let disEndDate = ref('')

const canSubmit = computed(() => {
  return (
    tableInfo.selections.filter((item) => item.status !== 1).length === 0 &&
    tableInfo.selections.length !== 0
  )
})
const canStorage = computed(() => {
  return (
    tableInfo.selections.filter((item) => item.status !== 2).length === 0 &&
    tableInfo.selections.length !== 0
  )
})
const canPendStoreRevoke = computed(() => {
  return (
    tableInfo.selections.filter((item) => item.status !== 2).length === 0 &&
    tableInfo.selections.length !== 0
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'receivingOrder' && el.url === val.url) {
                addDeliverDialog.visible = false
                modifyDeliverInfo.visible = false
                detailInfo.visible = false
                purchOrder.visible = false
                detailListInfo.visible = false
                preferenceInfo.visible = false
                selectDepotInfo.visible = false
                advancedSearchInfo.visible = false
                dialogUserInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId || val.orderId
                  sessionStorage.setItem(
                    'storeRowId',
                    val.businessId || val.orderId
                  )
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'receiving_order_status',
    show: false,
    hidden: true,
  },
  receiveStatusValue: {
    label: '收货状态',
    value: 'receiveStatusValue',
    asValue: 'receiveStatus',
    componentType: 'select-model',
    code: 'receiving_order_receive_status',
    show: false,
    hidden: true,
  },
  sourceTypeValue: {
    label: '来源单据类型',
    value: 'sourceTypeValue',
    asValue: 'sourceType',
    componentType: 'select-model',
    code: 'receiving_source_type',
    show: false,
    hidden: true,
  },
  fiscalPeriodName: {
    label: '会计期间',
    value: 'fiscalPeriodName',
    asValue: 'fiscalPeriodName',
    componentType: 'select-fiscal-period',
    query: {
      fiscalType: 1,
    }, //1 = 物资 2 = 资产
    highlightRow: true,
    checkBox: false,
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
getUserList()

function ifRenderRevoke(row = undefined) {
  if (
    proxy.$store.state.permission.systemConfig.material_receiving_approval === 1
  ) {
    return row.status === 6
  }
  return row.status === 2
}
//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: -2, userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.userList = arr.concat(data)
      }
    }
  })
}
//上架
function saveputShelfUser() {
  stockAndPutShelfReceivingOrder(formUserInfo.data).then((res) => {
    if (res && res.success) {
      getList()
      handleClose()
    }
  })
}
//关闭选择拣货人员弹窗
function handleClose() {
  dialogUserInfo.visible = false
  formUserInfo.data = {
    id: '',
    putShelfUser: -2,
  }
}
function create() {
  modifyInfo.orderId = ''
  modifyInfo.visible = true
  modifyInfo.title = '新增收货单'
}

function addDeliverBack(obj) {
  proxy.$nextTick(() => {
    if (obj.data && obj.data.id) {
      modifyDeliverInfo.deliverId = obj.data.id
      modifyDeliverInfo.orderId = ''
      modifyDeliverInfo.visible = true
      modifyDeliverInfo.title = '根据发货单导入'
      modifyDeliverInfo.receiveAll = obj.receiveAll
      modifyDeliverInfo.isEstimated = obj.isEstimated || false
    }
  })
}
function addBydeliver() {
  addDeliverDialog.visible = true
  addDeliverDialog.isEstimated = false
}
function addEstimated() {
  addDeliverDialog.visible = true
  addDeliverDialog.isEstimated = true
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  if (data.insertType === 1 && data.sourceType === 1) {
    //手动新增
    modifyInfo.orderId = data.id
    modifyInfo.visible = true
    modifyInfo.title = '修改收货单'
  } else {
    modifyDeliverInfo.orderId = data.id
    modifyDeliverInfo.deliverId = data.deliverId
    modifyDeliverInfo.visible = true
    modifyDeliverInfo.receiveAll = data.receiveAll
    modifyDeliverInfo.title = '修改收货单'
    modifyDeliverInfo.isEstimated = false
  }
}
//提交
function submit(row = undefined) {
  const ids = getIds(row)
  submitReceivingOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//审核
function check(row = undefined) {
  const ids = getIds(row)
  checkReceivingOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function reject(row = undefined) {
  const ids = getIds(row)
  rejectReceivingOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//入库
function storage(row = undefined, index) {
  const ids = getIds(row)
  if (row && row.id) {
    if (!tableLoading.value) {
      return
    }
    tableInfo.data[index]['loading'] = true
    tableLoading.value = false
  } else {
    btnLoading.value = true
  }
  storageReceivingOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
    if (row && row.id) {
      tableInfo.data[index]['loading'] = false
    }
    tableLoading.value = true
    btnLoading.value = false
  })
}
//取消上架
function _cancelPut(row = undefined) {
  proxy
    .$confirm('确认取消上架吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelPut(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
function storeAndPutShelf(row) {
  //方法名称
  dialogUserInfo.visible = true
  formUserInfo.data.id = row.id
  //stockAndPutShelfReceivingOrder
}
//多人验证弹窗关闭
function manyPeopleClose() {
  manyPeopleInfo.visible = false
  manyPeopleTable.data = []
}
//关闭弹窗
function close() {
  formInfo.data.id = ''
  formInfo.data.transferDepotId = ''
  formInfo.data.transferDeptId = ''
  formInfo.data.transferDepotName = ''
  formInfo.data.transferDeptName = ''
  selectDepotInfo.query.idNot = ''
  dialogTableInfo.data = []
  dialogInfo.value.visible = false
  dialogInfo.value.btList[1].disabled = true
}

//选择仓库
function selectStoreDepot() {
  selectDepotInfo.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data.transferDepotId = data.id
    formInfo.data.transferDepotName = data.name
    formInfo.data.transferDeptName = data.deptName || ''
    formInfo.data.transferDeptId = data.deptId || ''
    dialogInfo.value.btList[1].disabled = true
    getStorePath()
  } else {
    formInfo.data.transferDepotId = ''
    formInfo.data.transferDepotName = ''
    formInfo.data.transferDeptName = ''
    formInfo.data.transferDeptId = ''
  }
}
function getStorePath() {
  let param = {
    firstDepotId: dialogInfo.value.row.depotId,
    lastDepotId: formInfo.data.transferDepotId,
  }
  getDepotCirculationPath(param).then((res) => {
    if (res && res.success) {
      dialogTableInfo.data = res.data
      if (res.data.length > 0) {
        dialogInfo.value.path = res.data[0].value
      }
      dialogInfo.value.btList[1].disabled = false
    }
  })
}
function handleDialogEvent(event, data) {
  if (event === 'tableClickRow') {
    dialogInfo.value.path = data.value
  }
}
//查看明细
function showTransferDetail(row) {
  dialogInfo.value.visible = true
  dialogInfo.value.row = row
  formInfo.data.id = row.id
  selectDepotInfo.query.idNot = row.depotId
  setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
  setBusinessDate()
}
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
//入库并移库
function stockAndTransfer() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let many_people_verification =
        proxy.$store.state.permission.systemConfig.many_people_verification
      if (Number(many_people_verification) > 0) {
        manyPeopleTable.data = []
        for (let i = 0; i < Number(many_people_verification); i++) {
          manyPeopleTable.data.push({ username: '', password: '' })
        }
        manyPeopleInfo.visible = true
        return
      }
      submitStockAndTransfer()
    }
  })
}
//多人验证保存
function manyPeopleSave() {
  proxy.$refs.tableForm.validate((valid) => {
    if (valid) {
      let data = manyPeopleTable.data
      let newData = data.map((item) => {
        let encryptPassword = aesEncrypt(item.password, item.username.trim())
        return {
          username: item.username.trim(),
          password: encryptPassword.toString(),
        }
      })
      let param = {
        userList: newData,
        lastDepotId: formInfo.data.transferDepotId,
      }
      manyPeopleVerification(param).then((res) => {
        if (res && res.success) {
          manyPeopleClose()
          submitStockAndTransfer()
        }
      })
    }
  })
}
function submitStockAndTransfer() {
  let id = formInfo.data.id
  if (dialogTableInfo.data.length) {
    let params = {
      id: id,
      path: dialogInfo.value.path,
      businessDate: formInfo.data.businessDate,
    }
    stockAndTransferByPath(params).then((resp) => {
      if (resp && resp.success) {
        getList()
        close()
      }
    })
  } else {
    let params = {
      id: id,
      transferDeptId: formInfo.data.transferDeptId,
      transferDepotId: formInfo.data.transferDepotId,
      businessDate: formInfo.data.businessDate,
    }
    stockAndTransferReceivingOrder(params).then((resp) => {
      if (resp && resp.success) {
        getList()
        close()
      }
    })
  }
}
//查看明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.id = row.id
  detailInfo.isCargoSpaceManage = row.isCargoSpaceManage
  detailInfo.visible = true
}
//查看采购单明细
function showpurchOrderNoDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  purchOrder.purchOrderId = row.purchOrderId
  purchOrder.visible = true
}
//删除
function remove(row = undefined) {
  const ids = getIds(row)
  deleteReceivingOrder(ids).then((res) => {
    if (res && res.success) {
      search()
    }
  })
}
function getIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((row) => row.id)
  }
  return ids
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function tableRowClassName({ row }) {
  let receivingSwitchColor =
    proxy.$store.state.permission.systemConfig.receiving_switch_color
  let rowId = sessionStorage.getItem('storeRowId')
  if (receivingSwitchColor == 1) {
    if (rowId && row.id === Number(rowId)) {
      return 'check-row'
    } else {
      // if (!row.billNumberList) {
      //   return 'warning-row'
      // }
    }
  } else {
    if (rowId && row.id === Number(rowId)) {
      return 'check-row'
    }
  }
  return ''
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.query.queryMap.receivingTime.value = val[0] + ',' + val[1]
  } else {
    filterInfo.query.queryMap.receivingTime.value = null
  }
}
function revoke(row) {
  let ids = row ? [row.id] : tableInfo.selections.map((a) => a.id)
  revokeReceivingOrder(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function pendStoreRevoke(row) {
  let ids = row ? [row.id] : tableInfo.selections.map((a) => a.id)
  pendStoreRevokeReceivingOrder(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function invalid(row) {
  proxy
    .$confirm(
      '作废后入库库存必须出库；此条数据不能被入库报表统计, 是否确定作废?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      invalidReceivingOrder([row.id]).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'stockReceivingOrderList-com.slip.spd.entity.vo.stock.ReceivingOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      // filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList = [
        ...searchInfo.searchList,
        {
          label: '发票号汇总',
          value: 'receiptNumber',
          slot: 'true',
        },
        {
          label: '无票查询',
          value: 'noneReceiptNumber',
          slot: 'true',
        },
      ]
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getReceivingOrderCustomizeListPage
      proxy.$nextTick(() => {
        filterInfo.query.queryMap = {
          ...proxy.$fn.deepClone(filterInfo.query.queryMap),
          ...proxy.$fn.deepClone(searchInfo.queryMap),
        }
        filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
        getList()
      })
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

function checkBindUDI(row){
  bindUDIInfo.value.row = row
  bindUDIInfo.value.visible = true
}
</script>

<style scoped lang="scss">
:deep(.el-table .warning-row) {
  background: #f5e4e4;
}
</style>
